package GUI;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTabbedPane;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JLabel;

import java.awt.Font;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.RowFilter;
import javax.swing.SwingConstants;
import javax.swing.border.TitledBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import javax.swing.UIManager;

import model.Case;
import control.*;
import db.DBCase;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class cases extends JFrame {

	private final TableRowSorter<TableModel> sorter;
	private JPanel contentPane;
	private JTextField tfClientCvr;
	private JTextField tfDebtorCpr;
	private JTextField tfLicensePlate;
	private JTextField tfDebt;
	private JTextField tfSearch;
	private JTable casesTable;
	private PersonCtrl personCtrl = new PersonCtrl();
	private ClientCtrl clientCtrl = new ClientCtrl();
	private VehicleCtrl vehicleCtrl = new VehicleCtrl();
	private CaseCtrl caseCtrl = new CaseCtrl();
	private JComboBox contractCombo;
	private JTextPane txtInfo;
	private clients clientM = new clients();
	private debtors debtorM = new debtors();
	private vehicles vehicleM = new vehicles();
	private casesTable casesT = new casesTable();
	private workOnCase workOnCase = new workOnCase();
	private cases frame;
	private String user = "";
	private JButton btnDeleteCase;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					//frame = new cases();
					//frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	
	
	/**
	 * Create the frame.
	 */
	public cases() {
		setBackground(new Color(255, 255, 153));
		setTitle("CASES MENU");
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setBounds(100, 100, 950, 600);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
		tabbedPane.setBackground(new Color(255, 255, 153));
		tabbedPane.setBounds(0, 0, 934, 562);
		contentPane.add(tabbedPane);
		
		JPanel panelFind = new JPanel();
		panelFind.setBackground(new Color(255, 255, 153));
		tabbedPane.addTab("     FIND CASE      ", null, panelFind, null);
		panelFind.setLayout(null);
		
		JLabel lblSearchBy = new JLabel("Search :");
		lblSearchBy.setHorizontalAlignment(SwingConstants.RIGHT);
		lblSearchBy.setFont(new Font("Times New Roman", Font.PLAIN, 15));
		lblSearchBy.setBounds(10, 61, 110, 30);
		panelFind.add(lblSearchBy);
		
		tfSearch = new JTextField();
		tfSearch.setBounds(130, 62, 150, 30);
		panelFind.add(tfSearch);
		tfSearch.setColumns(10);
		tfSearch.getDocument().addDocumentListener(new DocumentListener() {  // <---
            @Override
            public void removeUpdate(DocumentEvent e) {
                filter();
            }
             
            @Override
            public void insertUpdate(DocumentEvent e) {
                filter();
            }
             
            @Override
            public void changedUpdate(DocumentEvent e) {}
        });
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(10, 103, 909, 420);
		panelFind.add(scrollPane);
		
		casesTable = new JTable();
		casesTable.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][]{},
                new String []
                {
                			"ID", "Start Date", "License Plate", "Client CVR", "Debtor CPR", "End Date", "Work"
                }));
		 sorter = new TableRowSorter<TableModel>(casesT);
		 casesTable.setRowSorter(sorter);
		scrollPane.setViewportView(casesTable);
		
		JLabel lblCasesList = new JLabel("List of Cases");
		lblCasesList.setHorizontalAlignment(SwingConstants.CENTER);
		lblCasesList.setFont(new Font("Times New Roman", Font.BOLD, 24));
		lblCasesList.setBounds(10, 11, 909, 40);
		panelFind.add(lblCasesList);
		
		btnDeleteCase = new JButton("Delete Case");
		btnDeleteCase.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int reply = JOptionPane.showConfirmDialog(null, "Are you sure you want to delete case?.",
						"Delete Case", JOptionPane.YES_NO_OPTION);
				if(reply == JOptionPane.YES_NO_OPTION)
				{
					int row = casesTable.getSelectedRow();
		      	    String id = (String)casesTable.getModel().getValueAt(row, 0);
		      	    caseCtrl.deleteCaseAssociations(id);
		      	    caseCtrl.deleteCase(id);
		      	    updateCaseTable();
		      	    JOptionPane.showMessageDialog(null,"Case has been deleted.");
				}
			}
		});
		btnDeleteCase.setFont(new Font("Times New Roman", Font.BOLD, 17));
		btnDeleteCase.setBounds(793, 61, 126, 31);
		panelFind.add(btnDeleteCase);
		
		JPanel panelCreate = new JPanel();
		panelCreate.setBackground(new Color(255, 255, 153));
		tabbedPane.addTab("    CREATE CASE     ", null, panelCreate, null);
		panelCreate.setLayout(null);
		
		JPanel panel = new JPanel();
		panel.setBackground(new Color(255, 255, 153));
		panel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Enter CVR and press the X button", TitledBorder.RIGHT, TitledBorder.TOP, null, null));
		panel.setBounds(29, 40, 279, 54);
		panelCreate.add(panel);
		panel.setLayout(null);
		
		JLabel label = new JLabel("CLIENT CVR :");
		label.setBounds(6, 16, 138, 31);
		panel.add(label);
		label.setHorizontalAlignment(SwingConstants.RIGHT);
		label.setFont(new Font("Times New Roman", Font.PLAIN, 15));
		
		tfClientCvr = new JTextField();
		tfClientCvr.setBounds(154, 20, 119, 25);
		panel.add(tfClientCvr);
		tfClientCvr.setColumns(10);
		
		JPanel panel_1 = new JPanel();
		panel_1.setBackground(new Color(255, 255, 153));
		panel_1.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Enter CPR and press the X button", TitledBorder.RIGHT, TitledBorder.TOP, null, null));
		panel_1.setBounds(29, 150, 279, 54);
		panelCreate.add(panel_1);
		panel_1.setLayout(null);
		
		JLabel lblDebtorCpr = new JLabel("DEBTOR CPR :");
		lblDebtorCpr.setBounds(6, 16, 138, 31);
		panel_1.add(lblDebtorCpr);
		lblDebtorCpr.setHorizontalAlignment(SwingConstants.RIGHT);
		lblDebtorCpr.setFont(new Font("Times New Roman", Font.PLAIN, 15));
		
		tfDebtorCpr = new JTextField();
		tfDebtorCpr.setBounds(154, 20, 119, 25);
		panel_1.add(tfDebtorCpr);
		tfDebtorCpr.setColumns(10);
		
		JPanel panel_3 = new JPanel();
		panel_3.setBackground(new Color(255, 255, 153));
		panel_3.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Enter License Plate and press the X button", TitledBorder.RIGHT, TitledBorder.TOP, null, null));
		panel_3.setBounds(29, 260, 279, 54);
		panelCreate.add(panel_3);
		panel_3.setLayout(null);
		
		JLabel lblLicensePlate = new JLabel("LICENSE PLATE :");
		lblLicensePlate.setBounds(6, 16, 138, 31);
		panel_3.add(lblLicensePlate);
		lblLicensePlate.setHorizontalAlignment(SwingConstants.RIGHT);
		lblLicensePlate.setFont(new Font("Times New Roman", Font.PLAIN, 15));
		
		tfLicensePlate = new JTextField();
		tfLicensePlate.setBounds(154, 20, 119, 25);
		panel_3.add(tfLicensePlate);
		tfLicensePlate.setColumns(10);
		
		JPanel panel_2 = new JPanel();
		panel_2.setBackground(new Color(255, 255, 153));
		panel_2.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Choose kind of Contract", TitledBorder.RIGHT, TitledBorder.TOP, null, null));
		panel_2.setBounds(430, 150, 279, 54);
		panelCreate.add(panel_2);
		panel_2.setLayout(null);
		
		JLabel lblStartDate = new JLabel("CONTRACT :");
		lblStartDate.setBounds(6, 16, 138, 31);
		panel_2.add(lblStartDate);
		lblStartDate.setHorizontalAlignment(SwingConstants.RIGHT);
		lblStartDate.setFont(new Font("Times New Roman", Font.PLAIN, 15));
		
		contractCombo = new JComboBox();
		contractCombo.setBounds(154, 22, 119, 20);
		panel_2.add(contractCombo);
		
		DefaultComboBoxModel<String> accessModel = new DefaultComboBoxModel<String>();
        accessModel.addElement("Lease");
        accessModel.addElement("Bank loan");
        contractCombo.setModel(accessModel);
        contractCombo.setSelectedIndex(-1);
		
		JPanel panel_4 = new JPanel();
		panel_4.setBackground(new Color(255, 255, 153));
		panel_4.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Enter Debt if applicable", TitledBorder.RIGHT, TitledBorder.TOP, null, null));
		panel_4.setBounds(430, 40, 279, 54);
		panelCreate.add(panel_4);
		panel_4.setLayout(null);
		
		JLabel lblDebt = new JLabel("DEBT :");
		lblDebt.setBounds(6, 16, 138, 31);
		panel_4.add(lblDebt);
		lblDebt.setHorizontalAlignment(SwingConstants.RIGHT);
		lblDebt.setFont(new Font("Times New Roman", Font.PLAIN, 15));
		
		tfDebt = new JTextField();
		tfDebt.setBounds(154, 20, 119, 25);
		panel_4.add(tfDebt);
		tfDebt.setColumns(10);
		
		JLabel lblInformation = new JLabel("CASE ADITIONAL INFORMATION :");
		lblInformation.setFont(new Font("Times New Roman", Font.PLAIN, 15));
		lblInformation.setBounds(29, 343, 292, 31);
		panelCreate.add(lblInformation);
		casesT.setUser(user);
		
		casesTable.addMouseListener(new MouseAdapter() {
	      	  public void mouseClicked(MouseEvent e) {
	      	    if (e.getClickCount() == 2) {
	      	      JTable target = (JTable)e.getSource();
	      	      int row = target.getSelectedRow();
	      	      workOnCase.setVisible(true);
	      	      workOnCase.setUser(user);
	      	      workOnCase.setTextFields(caseCtrl.getCaseById((String)casesTable.getModel().getValueAt(row, 0)));
	      	      //casesT.setUser(user);
	      	      workOnCase.setCase(frame);
	      	    }
	      	  }
	      	});
		
		JButton btnAddCase = new JButton("Add case");
		btnAddCase.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(ifEmpty()) return;
				if(ifClientExists() == false)
        		{
        			JOptionPane.showMessageDialog(null,"Cient with this CVR does not exist.");
        			return;
        		}
				if(ifDebtorExists() == false)
        		{
        			JOptionPane.showMessageDialog(null,"Debtor with this CPR does not exist.");
        			return;
        		}
				if(ifVehicleExists() == false)
        		{
        			JOptionPane.showMessageDialog(null,"Vehicle with this License Plate number does not exist.");
        			return;
        		}
				try
				{
					caseCtrl.createCase(tfClientCvr.getText(), tfDebtorCpr.getText(), tfLicensePlate.getText(),
							txtInfo.getText(), tfDebt.getText(), (String)contractCombo.getSelectedItem());
					JOptionPane.showMessageDialog(null,"Case has been successfuly created.");
					updateCaseTable();
					clearTextFields();
				}
				catch(Exception r)
				{
					JOptionPane.showMessageDialog(null,"Error in creating Case.");
				}
			}
		});
		btnAddCase.setFont(new Font("Times New Roman", Font.BOLD, 17));
		btnAddCase.setBounds(780, 455, 126, 31);
		panelCreate.add(btnAddCase);
		
		JScrollPane scrollPane_1 = new JScrollPane();
		scrollPane_1.setBounds(29, 385, 508, 100);
		panelCreate.add(scrollPane_1);
		
		txtInfo = new JTextPane();
		scrollPane_1.setViewportView(txtInfo);
		
		JButton btnXclient = new JButton("X");
		btnXclient.addActionListener(new ActionListener(
				) {
			public void actionPerformed(ActionEvent e) {
				if(ifClientExists())
				{
					tfClientCvr.setBackground(Color.GREEN);
					return;
				}
				else
				{
					int reply = JOptionPane.showConfirmDialog(null, "Client with this CVR does not exist. Do you want to create?",
							"Error", JOptionPane.YES_NO_OPTION);
					if(reply == JOptionPane.YES_NO_OPTION)
					{
						clientM.updateClientTable();
						clientM.setVisible(true);
					}
				}
			}
		});
		btnXclient.setBounds(318, 50, 45, 43);
		panelCreate.add(btnXclient);
		
		JButton btnXdebtor = new JButton("X");
		btnXdebtor.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(ifDebtorExists())
				{
					tfDebtorCpr.setBackground(Color.GREEN);
					return;
				}
				else
				{
					int reply = JOptionPane.showConfirmDialog(null, "Debtor with this CPR does not exist. Do you want to create?",
							"Error", JOptionPane.YES_NO_OPTION);
					if(reply == JOptionPane.YES_NO_OPTION)
					{
						debtorM.updateDebtorTable();
						debtorM.setVisible(true);
					}
				}
			}
		});
		btnXdebtor.setBounds(318, 160, 45, 43);
		panelCreate.add(btnXdebtor);
		
		JButton btnXlicensePlate = new JButton("X");
		btnXlicensePlate.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(ifVehicleExists())
				{
					tfLicensePlate.setBackground(Color.GREEN);
					return;
				}
				else
				{
					int reply = JOptionPane.showConfirmDialog(null, "Vehicle with this License Plate number does not exist. Do you want to create?",
							"Error", JOptionPane.YES_NO_OPTION);
					if(reply == JOptionPane.YES_NO_OPTION)
					{
						vehicleM.updateVehicleTable();
						vehicleM.setVisible(true);
					}
				}
			}
		});
		btnXlicensePlate.setBounds(318, 270, 45, 43);
		panelCreate.add(btnXlicensePlate);
	}
	
	public boolean ifEmpty()
    {
            if(tfClientCvr.getText().equals("") || tfDebtorCpr.getText().equals("") || tfLicensePlate.getText().equals(""))
            {
                    JOptionPane.showMessageDialog(null,"Some of the fields are empty.");
                    return true;
            }
            if(contractCombo.getSelectedIndex() == -1)
            {
                    JOptionPane.showMessageDialog(null,"Contract type is not selected.");
                    return true;
            }
            return false;
    }
	
	public boolean ifClientExists()
    {
    	if(clientCtrl.getClientByCvr(tfClientCvr.getText()) != null)
    		return true;
    	return false;
    }
	
	public boolean ifDebtorExists()
    {
    	if(personCtrl.getDebtorByCpr(tfDebtorCpr.getText()) != null)
    		return true;
    	return false;
    }
	
	public boolean ifVehicleExists()
    {
    	if(vehicleCtrl.getVehicleByLicensePlate(tfLicensePlate.getText()) != null)
    		return true;
    	return false;
    }
	
	public void clearTextFields()
    {
            tfClientCvr.setText("");
            tfDebtorCpr.setText("");
            tfLicensePlate.setText("");
            tfDebt.setText("");
            txtInfo.setText("");
            contractCombo.setSelectedIndex(-1);
            tfClientCvr.setBackground(Color.WHITE);
            tfDebtorCpr.setBackground(Color.WHITE);
            tfLicensePlate.setBackground(Color.WHITE);
    }
	
	public void updateCaseTable()
    {
		casesT.setCase(caseCtrl.listAllCases());
		casesTable.setModel(casesT);
    }
	
	public void setFrame(cases _frame)
	{
		frame = _frame;
	}
	
	protected void filter()
	{
        sorter.setRowFilter(RowFilter.regexFilter("^(?i)"+tfSearch.getText()));
    }
	
	public void setUser(String _user)
	{
		user = _user;
	}
	
	public void setTableUser(String _user)
	{
		casesT.setUser(user);
	}
	
	public void setAccessType(String _accessType)
    {
    	
            if(_accessType.equals("Full Access"))
            {
            	btnDeleteCase.setVisible(true);
            }
            if(_accessType.equals("Limited Access"))
            {
            	btnDeleteCase.setVisible(false);
            }
    }
}
